package com.north.light.libosspic;

import android.text.format.DateFormat;
import android.util.Log;

import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * Created by lzt
 * time 2020/8/15
 * 描述：
 * https://'+config().dev+'/ysp_h5/oss/ali/authorizationUrl?folderName=
 */
public class UploadHelper {


    private static OSS getOSSClient() {
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(OSSConstant.OSS_PIC_KEY, OSSConstant.OSS_PIC_VALUE);
        return new OSSClient(OSSPicManager.getInstance().getContext(), OSSConstant.OSS_PIC_ENDPOINT, credentialProvider);
    }

    /**
     * 上传方法
     *
     * @param objectKey 标识
     * @param path      需上传文件的路径
     * @return 外网访问的路径
     */
    private static String upload(String objectKey, String path) {
        // 构造上传请求
        PutObjectRequest request = new PutObjectRequest(OSSConstant.OSS_PIC_BUCKET_NAME, objectKey, path);
        try {
            //得到client
            OSS client = getOSSClient();
            //上传获取结果
            PutObjectResult result = client.putObject(request);
            //获取可访问的url
            String url = client.presignPublicObjectURL(OSSConstant.OSS_PIC_BUCKET_NAME, objectKey);
            //格式打印输出
            Log.e("upload", String.format("PublicObjectURL:%s", url));
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 上传普通图片
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadImage(String path) {
        String key = getObjectImageKey(path);
        return upload(key, path);
    }

//    /**
//     * 上传头像
//     *
//     * @param path 本地地址
//     * @return 服务器地址
//     */
//    public static String uploadPortrait(String path) {
//        String key = getObjectPortraitKey(path);
//        return upload(key, path);
//    }
//
//    /**
//     * 上传audio
//     *
//     * @param path 本地地址
//     * @return 服务器地址
//     */
//    public static String uploadAudio(String path) {
//        String key = getObjectAudioKey(path);
//        return upload(key, path);
//    }


    /**
     * 获取时间
     *
     * @return 时间戳 例如:201805
     */
    private static String getDateString() {
        return DateFormat.format("yyyyMM", new Date()).toString();
    }

    /**
     * 返回key
     *
     * @param path 本地路径
     * @return key
     */
    private static String getObjectImageKey(String path) {
        String fileMd5 = getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("androidpic/%s/%s.jpg", dateString, fileMd5);
    }

    private static String getObjectPortraitKey(String path) {
        String fileMd5 = getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("androidportrait/%s/%s.jpg", dateString, fileMd5);
    }

    private static String getObjectAudioKey(String path) {
        String fileMd5 = getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("androidaudio/%s/%s.mp3", dateString, fileMd5);
    }


    //转码------------------------------------------------------------------------------------------------
    private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'};

    private static String convertToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (byte a : b) {
            sb.append(HEX_DIGITS[(a & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[a & 0x0f]);
        }
        return sb.toString();
    }

    /**
     * Get a String's HashCode
     *
     * @param str String
     * @return HashCode
     */
    public static String getMD5String(String str) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        md5.update(str.getBytes());
        return convertToHexString(md5.digest());
    }

    /**
     * Get a File's HashCode
     *
     * @param file File
     * @return HashCode
     */
    public static String getMD5String(File file) {
        // Create md5
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        // Stream
        InputStream in = null;
        byte[] buffer = new byte[1024];
        int numRead;
        // Read
        try {
            in = new FileInputStream(file);
            while ((numRead = in.read(buffer)) > 0) {
                md5.update(buffer, 0, numRead);
            }
            return convertToHexString(md5.digest());
        } catch (Exception e) {
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
